package com.atmilan.quartz.utils.product;

import cn.hutool.core.date.DateUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.alibaba.fastjson.JSONObject;
import com.atmilan.quartz.config.RestTemplateConfig;
import com.atmilan.quartz.model.dto.lavita.LavitaProductResDTO;
import com.atmilan.quartz.model.dto.lavita.LavitaProductSkuRes;
import com.atmilan.quartz.model.dto.lavita.LavitaProductStockRes;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.Arrays;
import java.util.Date;

/**
 * 拉取商品源数据
 */

@Slf4j
@Service
public class LavitaProductUtil {

    @Autowired
    private RestTemplateConfig restTemplateConfig;

    @Value("${lavita.appid}")
    private String lavitaAppid;
    @Value("${lavita.appsecret}")
    private String lavitaAppsecret;
    @Value("${lavita.url.domain}")
    private String lavitaDomian;
    @Value("${lavita.url.products}")
    private String lavitaProducts;
    @Value("${lavita.url.productInfo}")
    private String productInfo;
    @Value("${lavita.url.stocks}")
    private String lavitaStocks;

    /**
     * 查询分页商品数据
     * @Description:
     * @author songjc
     * @param @param pageNow
     * @param @param pageSize
     * @param @return
     * @param @throws Exception
     * @return InProductResDTO
     * @throws
     */
    public LavitaProductResDTO selectLavitaPage(int pageNum, int pageSize) {
        // 组装请求url
        LavitaProductResDTO lavitaProductResDTO=null;
        try {
            StringBuilder url = new StringBuilder();
            url.append(lavitaDomian);
            url.append(lavitaProducts);
            url.append("?appid=");
            url.append(lavitaAppid);
            // 发送请求
            RestTemplate restTemplate = restTemplateConfig.restTemplate();
            HttpHeaders headers = new HttpHeaders();
            headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));

            JSONObject jsonObject = new JSONObject();
            //设置参数
            //生成令牌
            String lavitaToken = DigestUtil.md5Hex("appid="+lavitaAppid+"&appsecret="+lavitaAppsecret+"&times="+ DateUtil.format(new Date(),"yyyy-MM-dd"));
            jsonObject.put("token", lavitaToken);
            jsonObject.put( "limit", pageSize);
            jsonObject.put( "offset",pageNum);

            HttpEntity<String> request = new HttpEntity(jsonObject, headers);
            ResponseEntity<String> response = restTemplate.exchange(url.toString(), HttpMethod.POST, request, String.class);

            if (HttpStatus.OK != response.getStatusCode()) {
                JSONObject message = JSONObject.parseObject(response.getBody());
                String errorMessage = message.getString("error");

                log.info("--------------- lavita查询分页商品数据异常{} ---------------", errorMessage);
            }

            ObjectMapper mapper = new ObjectMapper();
            lavitaProductResDTO = mapper.readValue(response.getBody(), LavitaProductResDTO.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return lavitaProductResDTO;
    }

    /**
     * 获取单个商品sku
     * @param kuanId
     * @return
     */
    public LavitaProductSkuRes getLavitaSku(String kuanId) {
        // 组装请求url
        LavitaProductSkuRes lavitaProductSkuRes = null;
        try {
            StringBuilder url = new StringBuilder();
            url.append(lavitaDomian);
            url.append(productInfo);
            url.append("?appid=");
            url.append(lavitaAppid);
            // 发送请求
            RestTemplate restTemplate = restTemplateConfig.restTemplate();
            HttpHeaders headers = new HttpHeaders();
            headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));

            JSONObject jsonObject = new JSONObject();
            //设置参数
            //生成令牌
            String lavitaToken = DigestUtil.md5Hex("appid="+lavitaAppid+"&appsecret="+lavitaAppsecret+"&times="+DateUtil.format(new Date(),"yyyy-MM-dd"));
            jsonObject.put("token", lavitaToken);
            jsonObject.put( "kuanId",kuanId);
            jsonObject.put( "SearchEqual", 0);

            HttpEntity<String> request = new HttpEntity(jsonObject, headers);
            ResponseEntity<String> response = restTemplate.exchange(url.toString(), HttpMethod.POST, request, String.class);


            if (HttpStatus.OK != response.getStatusCode()) {
                JSONObject message = JSONObject.parseObject(response.getBody());
                String errorMessage = message.getString("error");

                log.info("--------------- Lavita获取单个商品sku异常{} ---------------", errorMessage);
            }
            ObjectMapper mapper = new ObjectMapper();

            lavitaProductSkuRes = mapper.readValue(response.getBody(), LavitaProductSkuRes.class);
            lavitaProductSkuRes.getDataDetail().setKuanId(kuanId);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return lavitaProductSkuRes;
    }

    /**
     * 获取单个商品sku
     * @param value
     * @return
     */
    public LavitaProductStockRes getLavitaDetail(String value) {
        // 组装请求url
        StringBuilder url = new StringBuilder();
        url.append(lavitaDomian);
        url.append(lavitaStocks);
        url.append("?appid=");
        url.append(lavitaAppid);
        // 发送请求
        RestTemplate restTemplate = restTemplateConfig.restTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));

        JSONObject jsonObject = new JSONObject();
        //设置参数
        //生成令牌
        String lavitaToken = DigestUtil.md5Hex("appid="+lavitaAppid+"&appsecret="+lavitaAppsecret+"&times="+DateUtil.format(new Date(),"yyyy-MM-dd"));
        jsonObject.put("token", lavitaToken);
        jsonObject.put( "likeEqualValue",value);
        jsonObject.put( "limit","1000");
        jsonObject.put( "offset", "0");
        jsonObject.put( "likeEqual", "4");
        jsonObject.put( "orderType", "0");

        HttpEntity<String> request = new HttpEntity(jsonObject, headers);
        ResponseEntity<String> response = restTemplate.exchange(url.toString(), HttpMethod.POST, request, String.class);


        if (HttpStatus.OK != response.getStatusCode()) {
            JSONObject message = JSONObject.parseObject(response.getBody());
            String errorMessage = message.getString("error");

            log.info("--------------- Lavita获取单个商品库存异常{} ---------------", errorMessage);
        }
        ObjectMapper mapper = new ObjectMapper();
        LavitaProductStockRes lavitaProductStockRes = null;
        try {
            lavitaProductStockRes = mapper.readValue(response.getBody(), LavitaProductStockRes.class);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return lavitaProductStockRes;
    }

}
